unit uProfiler;

interface

uses
  Classes, Windows;
  
type
  TProfiler = class(TThread)
  private
    FEvent: THandle;
    FLogFile: THandle;
  protected
    procedure Execute; override;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Trace(const msg: string);
  end;

var
  G_Profiler: TProfiler;
implementation

uses
  SysUtils;
  
{ TProfiler }

constructor TProfiler.Create;
begin
  inherited Create(False);
  FEvent := CreateEvent(nil, True, False, nil);
  FLogFile := CreateFile(PChar(ExtractFilePath(ParamStr(0)) + 'log.txt'),
                        GENERIC_WRITE,
                        FILE_SHARE_READ,
                        nil,
                        OPEN_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        0);
  if FLogFile<>0 then
  begin
    SetFilePointer(FLogFile, 0, nil, FILE_END);
  end;
end;

destructor TProfiler.Destroy;
begin
  if Suspended then
  begin
    Resume;
    Terminate;
    SetEvent(FEvent);
    WaitFor;
  end;
  if FLogFile<>0 then
    CloseHandle(FLogFile);
  CloseHandle(FEvent);
  inherited;
end;

procedure TProfiler.Execute;
begin
  while not Terminated do
  begin
    WaitforSingleObject(FEvent, 200);
  end;
end;

procedure TProfiler.Trace(const msg: string);
var
  strLine: string;
  count: DWord;
begin
  if FLogFile<>0 then
  begin
    strLine := DateTimeToStr(Now) + ' ' + Msg + #13#10;
    WriteFile(FLogFile, PChar(strLine)^, Length(strLine), count, nil);
  end;
end;

end.
